<?php
/**
 * 工单绑定延期原因
 * User: Administrator
 * Date: 2018/8/5/005
 * Time: 20:11
 */

namespace app\lib\Order\OrderExtensionConfig;


use app\lib\Order\IsOrder\IsOrder;
use app\model\OrderBindingExtensionModel;

class OrderBindingExtension
{
    protected $orderId;
    protected $opUid;
    protected $extensionId;
    public function __construct($orderId,$opUid,$extensionId)
    {
        $this->orderId = $orderId;
        $this->opUid   = $opUid;
        $this->extensionId = $extensionId;
    }
    /**
     * 数据检验
     * @return bool
     * @throws \Exception
     */
    protected function check(){
        $model =(new IsOrder($this->orderId));
        /*工单不存在或者工单不为进行中*/
        if(!$model->isExist() || !$model->isExecuteOrder()){
            exception('请传递有效工单号');
        }
        /*验证该标签是否存在*/
        if(!(new GetExtensionConfig($this->extensionId))->isExistAndUse()){
            exception('标签不存在或者已无法使用');
        }
        switch ($this->extensionId){
            case '1':
                /*验证该工单是否绑定了标签*/
                if((new GetOrderBindingExtension($this->orderId))->isOrderBindingSign()){
                    exception('该工单已绑定了待签收标签');
                }
                break;
            case '2':
                /*验证该工单是否绑定了标签*/
                if((new GetOrderBindingExtension($this->orderId))->isOrderBindingPay()){
                    exception('该工单已绑定了待交款标签');
                }
                break;
            default:
                /*验证该工单是否绑定了标签*/
                if((new GetOrderBindingExtension($this->orderId))->isOrderBindingDaily()){
                    exception('该工单已绑定了普通签收标签');
                }
                break;
        }
        return true;
    }

    /**
     * 执行代码
     * @return bool
     * @throws \Exception
     */
    public function save(){
        $this->check();
        $model =  new OrderBindingExtensionModel();
        $endTime = 0;
        if(!in_array($this->extensionId,[1,2])){
            $endTime =  $this->getEndTime();
        }
        $data = [
            $model->_status =>1,
            $model->_orderId=>$this->orderId,
            $model->_createTime=>time(),
            $model->_configId=>$this->extensionId,
            $model->_createId=>empty($this->opUid)?0:$this->opUid,
            $model->_endTime=>$endTime
        ];
        $result =  $model->insert($data);
        if(!$result){
            exception('绑定延期标签失败');
        }
        return true;
    }
    protected function getEndTime(){
        $configTime  = (new GetExtensionConfig($this->extensionId))->getConfigTime();
        return  time()+$configTime;
    }





}